package com.lemon.components.ant.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import com.lemon.components.common.result.ResultBase;

import lombok.experimental.UtilityClass;

@UtilityClass
public class FileUtil {

	public ResultBase copyFile(String srcPath,String destPath){
		ResultBase result = new ResultBase();
		File srcFile = new File(srcPath);
		if(!srcFile.exists()){
			result.setMessage("文件["+srcPath+"]不存在，拷贝失败。");
			return result;
		}
		File destFolder = new File(destPath).getParentFile();
		destFolder.mkdirs();
		try {
			byte[] tmp = new byte[100];
			FileInputStream fileInputStream = new FileInputStream(srcFile);
			FileOutputStream  fileOutputStream = new FileOutputStream(destPath);
			int readed = 0;
			while((readed = fileInputStream.read(tmp))>0){
				fileOutputStream.write(tmp,0,readed);
			}
			fileOutputStream.flush();
			fileOutputStream.close();
			fileInputStream.close();
		} catch (Exception e) {
			result.setMessage(e.getMessage());
			return result;
		}
		result.setSuccess(true);
		return result;
	}
	
	public ResultBase copyDir(String srcPath,String destPath){
		ResultBase result = new ResultBase();
		File dir = new File(srcPath);
		File destFile = new File(destPath);
		if(!dir.exists()){
			result.setMessage("文件夹["+srcPath+"]不存在，拷贝失败。");
			return result;
		}
		if(!destFile.exists()){
			destFile.mkdirs();
		}
		if(dir.list() != null){
			for(String name:dir.list()){
				File children = new File(srcPath+"/"+name);
				if(children.isFile()){
					copyFile(children.getAbsolutePath(),destFile.getAbsolutePath()+"/"+name);
				} else {
					copyDir(children.getAbsolutePath(),destFile.getAbsolutePath()+"/"+name);
				}
			}
		}
		result.setSuccess(true);
		result.setMessage("拷贝完成");
		return result;
	}
	
	public void batchDeleteMapper(PathUtil pathUtil,String...mapperNames) {
		for(String mapperName : mapperNames) {
			File deleteFile = new File(pathUtil.getMybatisMapperPath(),mapperName+".java");
			if(deleteFile.exists()) {
				deleteFile.delete();
				System.out.println("删除Mapper："+deleteFile.getAbsolutePath());
			}
			deleteFile = new File(pathUtil.getMybatisCustomizeMapperPath(),"My"+mapperName+".java");
			if(deleteFile.exists()) {
				deleteFile.delete();
				System.out.println("删除Mapper："+deleteFile.getAbsolutePath());
			}
		}
	}
	
	public void batchDeleteModel(PathUtil pathUtil,String...modelNames) {
		for(String modelName : modelNames) {
			File deleteFile = new File(pathUtil.getMybatisModelPath(),modelName+".java");
			if(deleteFile.exists()) {
				deleteFile.delete();
				System.out.println("删除Model："+deleteFile.getAbsolutePath());
			}
		}
	}
	
	public void batchDeleteMybatisXML(PathUtil pathUtil,String...xmls) {
		for(String xml : xmls) {
			File deleteFile = new File(pathUtil.getMybatisXMLPath(),xml+".xml");
			if(deleteFile.exists()) {
				deleteFile.delete();
				System.out.println("删除XML："+deleteFile.getAbsolutePath());
			}
			deleteFile = new File(pathUtil.getMybatisCustomizeXMLPath(),"My"+xml+".xml");
			if(deleteFile.exists()) {
				deleteFile.delete();
				System.out.println("删除XML："+deleteFile.getAbsolutePath());
			}
		}
	}
	
	/**
	 * 
	 * @param text 插入内容
	 * @param insertLine
	 * @param writeFile 文件路径
	 * @throws Exception 
	 */
	public void insertFile(String text,long insertLine,String writeFile) throws Exception {
		// 创建临时文件
        File tempFile = File.createTempFile("fileTmp", ".tmp");
        //  源文件
        File sourceFile = new File(writeFile);
        // 源文件输入流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));
        // 源文件输出流
        PrintWriter outPrinter = new PrintWriter(new FileOutputStream(tempFile));
        // 保存一行数据
        String thisLine;
        // jvm 退出 临时文件删除
        tempFile.deleteOnExit();
        int linNum= 1;
        while ((thisLine = bufferedReader.readLine()) != null) {
        //  当读取到目标行时 写入需要写入的内容
            if (linNum == insertLine) {
            	outPrinter.println(text);
            }
            // 输出读取到的数据
            outPrinter.println(thisLine);
            linNum++;
        }
        // 各种关
        outPrinter.flush();
        outPrinter.close();
        bufferedReader.close();
        // 删除原始文件
        sourceFile.delete();
        // 把临时文件改名为原文件名
        tempFile.renameTo(sourceFile);
	}
	
	public int totalRowFile(String file) throws Exception {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		int linNum= 0;
        while (bufferedReader.readLine() != null) {
        	linNum ++;
        }
        bufferedReader.close();
        return linNum;
	}
	
	public static void main(String[] args) throws Exception {
		String filePath="D:/workspace/myboot/src/main/java/com/lemon/components/ant/apimaker/enums/ResultType.java";
		int line = FileUtil.totalRowFile(filePath);
		System.out.println(line);
		FileUtil.insertFile("// test insert", line, filePath);
	}
}